/*
 * ClassPath.cpp
 *
 *  Created on: Nov 11, 2010
 *      Author: dhovemey
 */

#include <cstdio>
#include "util/String.h"
#include "util/Error.h"
#include "util/InputStreamReader.h"
#include "runtime/VirtualMachineException.h"
#include "runtime/ClassPath.h"

ClassPath::ClassPath()
{

}

ClassPath::~ClassPath()
{

}

std::string ClassPath::getRelativeFileNameForClassName(const std::wstring &clsName)
{
	std::string clsNameNarrow(String::toUtf8(clsName));
	return String::replace(clsNameNarrow, "::", "/") + ".thud";
}

void ClassPath::addDirectory(const std::wstring &dirName)
{
	m_clsPath.push_back(dirName);
}

bool ClassPath::readSourceForClass(const std::wstring &clsName, Reader *&reader, std::string &fileName) const
{
	std::string relativeFileName(getRelativeFileNameForClassName(clsName));

	for (DirList::const_iterator i = m_clsPath.begin(); i != m_clsPath.end(); i++) {
		std::string dirNarrow(String::toUtf8(*i));
		std::string sourceFileName(dirNarrow + "/" + relativeFileName);

		//printf("Looking for %s...\n", sourceFileName.c_str());

		Reader *reader_ = InputStreamReader::readFile(sourceFileName);
		if (reader_) {
			reader = reader_;
			fileName = sourceFileName;
			return true;
		}
		Error::raise(0);
	}
	Error::raise(new VirtualMachineException(L"Could not find source file for " + clsName));
	return false;
}
